﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.IO;
using System.ServiceProcess;
using System.Text;
using System.Windows.Forms;


namespace FolderSyncApp
{
    public partial class frmHSBN : Form
    {
        private ServiceController controller = new ServiceController("FolderSyncService");
        private readonly string EVENTLOG_NAME = "Sync_Log";
        //private readonly string LOG_FILE = "FolderSyncLog.txt";
        private FolderSyncConfig _config;
        public frmHSBN()
        {
            InitializeComponent();
        }

        private void frmHSBN_Load(object sender, EventArgs e)
        {
            try
            {
                _config = new FolderSyncConfig();
                lblFolderSync.Text = _config.FolderSyncParam;
                ClearEventLog();
                timer1.Interval = 1000;
                timer1.Enabled = true;
                CheckStatusService();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
            
        }

        /// <summary>
        /// Refresh service status
        /// </summary>
        public void CheckStatusService()
        {
            controller.Refresh();
            if (controller.Status == ServiceControllerStatus.Running)
            {
                btnRunService.Text = "Stop Service";
                StartFileSystemWatcher();
            }
            else if (controller.Status == ServiceControllerStatus.Stopped)
            {
                btnRunService.Text = "Start Service";
            }
        }
        /// <summary>
        /// Hàm khởi tạo FileSystemWatcher
        /// </summary>
        public void StartFileSystemWatcher()
        {
            try
            {
                FileSystemWatcher watch = new FileSystemWatcher();
                watch.Path = _config.FolderSyncParam;
                watch.Changed += new FileSystemEventHandler(OnChanged);
                watch.Created += new FileSystemEventHandler(OnChanged);
                watch.Deleted += new FileSystemEventHandler(OnChanged);
                watch.Renamed += new RenamedEventHandler(OnRenamed);
                watch.EnableRaisingEvents = true;
                watch.IncludeSubdirectories = true;
                //WriteLog(string.Format("Start Watching Folder {0}", _config.FolderSyncParam));
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
                //WriteLog(string.Format("Error Watching Folder {0} on {1}: {2}", _config.FolderSyncParam, DateTime.Now, ex.Message));
                //MessageBox.Show(string.Format("Error Watching Folder {0} on {1}: {2}", _config.FolderSyncParam, DateTime.Now,
                //                              ex.Message));
            }


        }

        //-------------------------------------------------- 
        private void OnChanged(object source, FileSystemEventArgs e)
        {
            // Specify what is done when a file is changed, created, or deleted. 
            ReadEventLog();
        }

        // ---------------------------------------------------------------------------------- 
        private void OnRenamed(object source, RenamedEventArgs e)
        {
            // Specify what is done when a file is renamed. 
            ReadEventLog();
        }

        
        //private void WriteLog(string content)
        //{
        //    TextWriter logFile = new StreamWriter(LOG_FILE, true);
        //    logFile.WriteLine(content);
        //    logFile.Close();
        //}

        private int currIndex = 0; //Lưu giá trị index đọc event log gần nhất

        /// <summary>
        /// Đọc event log và show ra
        /// </summary>
        private void ReadEventLog()
        {
            if (EventLog.Exists(EVENTLOG_NAME))
            {
                var eventLog = new EventLog(EVENTLOG_NAME);
                for (int i  = currIndex; i < eventLog.Entries.Count; i++)
                {

                    ListViewItem item = listViewLog.Items.Add(i.ToString(),
                                                              eventLog.Entries[i].TimeWritten.ToString(), -1);
                    if (eventLog.Entries[i].EntryType == EventLogEntryType.Error)
                    {
                        item.ForeColor = Color.Red;
                    }
                    else if (eventLog.Entries[i].EntryType == EventLogEntryType.Warning)
                    {
                        item.ForeColor = Color.Blue;
                    }
                    item.SubItems.Add(eventLog.Entries[i].Message);
                }
                currIndex = eventLog.Entries.Count;
            }
        }

        /// <summary>
        /// Xóa event log
        /// </summary>
        private void ClearEventLog()
        {
            try
            {
                if (EventLog.Exists(EVENTLOG_NAME))
                {
                    var eventLog = new EventLog(EVENTLOG_NAME);
                    eventLog.Clear();
                }
            }
            catch (Exception ex)
            {
                
                throw ex;
            }
            
        }
        private void btnRunService_Click(object sender, EventArgs e)
        {
            try
            {
                if (controller.Status == ServiceControllerStatus.Running)
                {
                    RunService.StopService(controller.ServiceName, 5000);
                }
                else if (controller.Status == ServiceControllerStatus.Stopped)
                {
                    RunService.StartService(controller.ServiceName, 5000);
                    
                }

                CheckStatusService();
                ReadEventLog();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void timer1_Tick(object sender, EventArgs e)
        {
            try
            {
                ReadEventLog();
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
        }

        private void btnSettings_Click(object sender, EventArgs e)
        {
            try
            {
                if (controller.Status == ServiceControllerStatus.Running)
                {
                    MessageBox.Show("Bạn phải stop service trước khi thay đổi config.");
                    return;
                }

                frmSettings frm = new frmSettings();
                frm.ShowDialog();
                //Reload config
                _config.Refresh();
                lblFolderSync.Text = _config.FolderSyncParam;
                
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
            
        }
    }
}
